package com.linciping.useges.plugin.writer;

import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.*;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.linciping.useges.plugin.util.PsiFileUtil;
import com.linciping.useges.plugin.view.UsegesWindowFactory;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public abstract class BaseUsegesWriter implements Runnable {

    private final Project project;
    private final PsiDirectory psiDirectory;

    public BaseUsegesWriter(Project project, PsiDirectory psiDirectory) {
        this.project = project;
        this.psiDirectory = psiDirectory;
    }

    @Override
    public void run() {
        if (psiDirectory == null) return;
        String fileName = getFileName();
        ImageIcon imageIcon = new ImageIcon(getClass().getResource("/toolWindow/Calendar-icon.png"));
        ToolWindowManager.getInstance(project).registerToolWindow(RegisterToolWindowTask.Companion.lazyAndClosable("useges_window",
                new UsegesWindowFactory(), imageIcon, ToolWindowAnchor.BOTTOM));
        PsiFile psiFile = PsiFileUtil.findPsiFileInPsiDirectory(psiDirectory, fileName);
        if (psiFile != null) psiFile.delete();
        psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, getFileType(), getContent());
        psiDirectory.add(psiFile);
    }

    abstract String getContent();

    abstract FileType getFileType();

    abstract String getFileName();
}
